package com.xyxy.platform.modules.service.trade.impl;

import com.google.common.collect.Lists;
import com.xyxy.platform.modules.core.cache.memcached.SpyMemcachedClient;
import com.xyxy.platform.modules.core.utils.Collections3;
import com.xyxy.platform.modules.entity.trade.GoodsServerTime;
import com.xyxy.platform.modules.entity.trade.GoodsServerTimeExample;
import com.xyxy.platform.modules.repository.mybatis.trade.GoodsServerTimeMapper;
import com.xyxy.platform.modules.service.trade.GoodsServerTimeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 简介:
 *
 * @author Caizhenegda
 * @version 1.0
 * @Date 2016-01-14 10:43
 */
@Service
public class GoodsServerTimeServiceImpl implements GoodsServerTimeService {

    @Autowired
    private GoodsServerTimeMapper goodsServerTimeMapper;

    @Autowired
    private SpyMemcachedClient memcachedClient;

    @Override
    @Transactional(readOnly = false)
    public Integer save(List<GoodsServerTime> serverTimeList, Long goodsId) {
        if (Collections3.isEmpty(serverTimeList)) return 0;
        // 删除原有
        this.delete(goodsId);
        //删除缓存
        memcachedClient.delete(this.getCacheKey(goodsId));
        //添加
        Integer row = 0; //受影响行数
        for (GoodsServerTime serverTime : serverTimeList) {
            serverTime.setGoodsId(goodsId);
            row += goodsServerTimeMapper.insert(serverTime);
        }
        return row;
    }

    @Override
    @Transactional(readOnly = true)
    public List<GoodsServerTime> findByGoodsId(Long goodsId) {
        List<GoodsServerTime> list = memcachedClient.get(this.getCacheKey(goodsId));
        if (Collections3.isNotEmpty(list)) return list;

        GoodsServerTimeExample sql = new GoodsServerTimeExample();
        sql.or().andGoodsIdEqualTo(goodsId);
        list = goodsServerTimeMapper.selectByExample(sql);
        //缓存 一个月
        memcachedClient.set(this.getCacheKey(goodsId), 60 * 60 * 24 * 30, list);
        return Collections3.isEmpty(list) ? Lists.<GoodsServerTime>newArrayList() : list;
    }

    @Override
    public Integer delete(Long goodsId) {
        if (null == goodsId) return 0;
        GoodsServerTimeExample sql = new GoodsServerTimeExample();
        sql.or().andGoodsIdEqualTo(goodsId);
        return goodsServerTimeMapper.deleteByExample(sql);
    }

    /**
     * 构建 服务时间段缓存 key
     *
     * @param goodsId
     * @return
     */
    private String getCacheKey(Long goodsId) {
        return "GoodsServerTimeServiceImpl_" + goodsId;
    }
}
